/// <reference path="../typings/tsd.d.ts" />

import fs = require("fs");
import async = require("async");

interface FileTreeHandler {
    (path: string, isDir: boolean, next: ErrorCallback): void;
}

function FileTreeWalker(root: string, handler: FileTreeHandler, completed?: ErrorCallback) {

    if (root.substr(-1) === "/") {

        root = root.substr(0, root.length - 1);
    }

    fs.readdir(root, function(err: Error, objs: string[]) {

        if (err) {

            completed(err);

            return;
        }

        async.forEachOf(objs, function(obj: string, index: number, next: ErrorCallback) {

            if (obj[0] === ".") {

                next();

                return;
            }

            let path = root + "/" + obj;

            fs.stat(path, function(err: Error, stats: fs.Stats) {

                if (err) {

                    next(err);
                    return;
                }

                if (stats.isFile()) {

                    handler(path, false, next);

                } else {

                    handler(path, true, function(err?: Error) {

                        if (err) {
                            next(err);
                            return;
                        }

                        FileTreeWalker(path, handler, next);
                    });

                }

            });

        }, function(err?: Error) {

            completed(err);

        });

    });
}

export = FileTreeWalker;
